//
//  CourseCodeViewController.m
//  jinnengExam
//
//  Created by mac on 2020/8/11.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "CourseCodeViewController.h"
#import <CoreImage/CoreImage.h>
#import <Masonry.h>
#import "SizeUtil.h"
#import "URLUtil.h"
#import "JZNRequestUtil.h"
#import "ScanDto.h"

@interface CourseCodeViewController ()
@property(nonatomic,strong) UIImageView *codeImageView;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) UILabel *label;
@end

@implementation CourseCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    self.title = @"课程签到";
    [self requestCode];
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestCode) userInfo:nil repeats:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void) initView{
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = [UIFont systemFontOfSize:16.0*LSCALE];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints: ^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10*LSCALE);
        make.width.equalTo(self.view.mas_width).offset(-20*LSCALE);
        make.centerX.equalTo(self.view);
    }];
    self.titleLabel.text = self.trainingClassName;
    
    self.codeImageView = [[UIImageView alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.codeImageView];
    [self.codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(SCREENSIZE.width*0.8);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(10*LSCALE);
    }];
    
    self.label = [[UILabel alloc]init];
    self.label.font = [UIFont systemFontOfSize:13.0*LSCALE];
    self.label.textColor = [UIColor redColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:self.label];
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(25);
        make.width.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.codeImageView.mas_bottom).offset(10*LSCALE);
    }];
    
}
-(void) requestCode{
    NSString *url = [NSString stringWithFormat:@"%@/classCourse/codeToClassCourse" ,[URLUtil hostName]];
    NSString *uuid = [self uuid];
    NSDictionary *params = @{@"code":uuid,@"classId":[self trainingClassId],@"signType":[self signType]};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            ScanDto *dto = [[ScanDto alloc]init];
            dto.operatonUrl = @"classCourse/userScanCode";
            dto.resultCode = uuid;
            self.codeImageView.image = [self createNonInterpolatedUIImageFormCIImage:[self creatQRcodeWithUrlstring:[dto mj_JSONString]] withSize:SCREENSIZE.width*0.8];
             self.label.text = @"";
        }else {
            UIImage *image = [UIImage imageNamed:@"logo.png"];
            self.codeImageView.image = image;
            self.label.text = @"生成二维码失败，请检查网络连接";
        }
    } failure:^(NSError *error) {
        NSLog(@"error");
    }];
}

-(NSString*) uuid{
    // create a new UUID which you own
    CFUUIDRef uuidref = CFUUIDCreate(kCFAllocatorDefault);
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    CFStringRef uuid = CFUUIDCreateString(kCFAllocatorDefault, uuidref);
    NSString *result = (__bridge NSString *)uuid;
    //release the uuidref
    CFRelease(uuidref);
    // release the UUID
    CFRelease(uuid);
    return result;
}
- (CIImage *)creatQRcodeWithUrlstring:(NSString *)urlString{
    
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
    [filter setDefaults];
    // 3.将字符串转换成NSdata
    NSData *data  = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
    [filter setValue:data forKey:@"inputMessage"];
    // 5.生成二维码
    CIImage *outputImage = [filter outputImage];
    return outputImage;
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
@end
